package com.company.project.controller.ldjsc.InternetInformation;

import com.company.project.common.utils.DataResult;

import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sxzy/listen")
@Api(tags = "领导驾驶仓-听")
public class ListenController {

    @ApiOperation(value = "听全文")
    @PostMapping("full/text")
//    @SaCheckPermission("zyMenu:add")
    @ResponseBody
    public Map<String, String> textToSpeech(@RequestBody Map<String, String> request) {
        String text = request.get("text");
        String voiceType = request.get("voiceType");

        // 生成临时文件名
        String timestamp = String.valueOf(System.currentTimeMillis());
        String pcmPath = "temp_" + timestamp + ".pcm";
        String wavPath = "temp_" + timestamp + ".wav";


        try {
            // 调用语音合成
            WebTtsWs webTts = new WebTtsWs();
            webTts.generateSpeech(text, pcmPath, wavPath, voiceType);

            // 将WAV文件转换为Base64
            String base64Audio = encodeFileToBase64(wavPath);

            // 返回Base64编码的音频数据
            Map<String, String> result = new HashMap<>();
            result.put("audio", base64Audio);
            result.put("status", "success");
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> result = new HashMap<>();
            result.put("status", "error");
            result.put("message", e.getMessage());
            return result;
        } finally {
            // 删除临时文件
            new File(pcmPath).delete();
            new File(wavPath).delete();
        }
    }

    /**
     * 将文件编码为Base64字符串
     */
    private String encodeFileToBase64(String filePath) throws IOException {
        File file = new File(filePath);
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }

            byte[] fileBytes = bos.toByteArray();
            return Base64.getEncoder().encodeToString(fileBytes);
        }
    }
}
